var server = {};

function InstallFunction(obj, functionName) {
    obj[functionName] = function() { request(functionName, arguments); }
}

//Request class based on the AJAX Google App Engine tutorial
function request(function_name, opt_argv) {
    if (!opt_argv)
        opt_argv = new Array();

    // Find if the last arg is a callback function; save it
    var callback = null;
    var len = opt_argv.length;
    if (len > 0 && typeof opt_argv[len-1] == 'function') {
        callback = opt_argv[len-1];
        opt_argv.length--;
    }
    var async = (callback != null);

    // Build an Array of parameters, w/ function_name being the first parameter
    var params = new Array(function_name);
    for (var i = 0; i < opt_argv.length; i++) {
        params.push(opt_argv[i]);
    }
    var body = JSON.stringify(params);

    var req = new XMLHttpRequest();
    req.open('POST', '/rpc', async);
    
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.setRequestHeader("Content-length", body.length);
    req.setRequestHeader("Connection", "close");
    
    if (async) {
        req.onreadystatechange = function() {
            if(req.readyState == 4 && req.status == 200) {
                var response = null;
                try {
                    response = JSON.parse(req.responseText);
                } catch (e) {
                    response = req.responseText;
                }
                callback(response);
            }
        }
    }

    req.send(body);
}

function addSerie(){
    if($("#addText").val().length > 0){
        $('#notification').jGrowl("<b>LOADING...</b>");
        server.AddSerie($("#addText").val(), updateComponents);
        $("#addText").val("");
    }
}

function updateComponents(serie){
    if(serie.length > 0){
        $("#tabFollow").html("Click on a Serie to see the Complete Airdate Calendar's:");
        $("<option value='"+serie+"'>"+serie+"</option>").appendTo("#comboNextEpisode");
        $("<option value='"+serie+"'>"+serie+"</option>").appendTo("#comboRemove");
        $("<li class='ui-widget-content'><a href='#'>"+serie+"</a></li>").appendTo("#selectable");
        $('#notification').jGrowl("<b>" + serie + ": Calendar Saved!</b>");
        date = new Date();
        server.UpdateTodayEpisodes(date.getDate(), date.getMonth(), date.getFullYear(), updateDateRelatedInfo);
    }else{
        $('#notification').jGrowl("<b>This Serie couldn't be loaded<br/>Please try again!<br/>Or reload the Page!<b>");
    }
}

function updateDateRelatedInfo(today){
    if(today != ""){
        $(".today").html("");
        for(var cal in today){
            val = "<li>" + today[cal].serie + " - " + today[cal].season + "x" + today[cal].nroEp + ": " + today[cal].episode + "</li>";
            $(val).appendTo(".today");
        }
        loadTable(today);
    }
}

function removeSerie(){
    serie = $("#comboRemove option:selected").text();
    server.RemoveSerie(serie, updateComponentsAfterRemove);
}

function updateComponentsAfterRemove(series){
    if(series != ""){
        $("#comboNextEpisode").html("");
        $("#comboRemove").html("");
        $("#selectable").html("");
        for(var cal in series){
            $("<option value='"+series[cal].serie+"'>"+series[cal].serie+"</option>").appendTo("#comboNextEpisode");
            $("<option value='"+series[cal].serie+"'>"+series[cal].serie+"</option>").appendTo("#comboRemove");
            $("<li class='ui-widget-content'><a href='#'>"+series[cal].serie+"</a></li>").appendTo("#selectable");
        }
        server.UpdateTodayEpisodes('', updateDateRelatedInfo);
    }
}

function checkNextEpisode(){
    serie = $("#comboNextEpisode option:selected").text();
    server.CheckNextEpisode(serie, showNextEpisode);
}

function showNextEpisode(data){
    if(data != ""){
        $('#notification').jGrowl("<b>" + data.serie + " Next Episode:<br/>"+data.date+"<br/>"+data.season+"x"+data.nroEp+": <br/>"+data.episode+"</b>");
    } else {
        $('#notification').jGrowl("<b>Next Episode Not Found!</b>");
    }
}

function obtainSerieInfo(serie){
    $('#notification').jGrowl("<b>LOADING...</b>");
    server.ObtainCalendarBySerie(serie, loadTableDialog);
}

function loadTable(cals){
    if(cals != ""){
        $("#tableBody").html("");
        var cant = 0;
        for(var cal in cals){
            cant++;
        }
        var i = 0;
        for(i = 0; i < cant; i++){
            val = "<tr><td>"+cals[i].serie+"</td><td>"+cals[i].season+"</td><td>"+cals[i].nroEp+"</td><td>"+cals[i].episode+"</td><td>"+cals[i].date+"</td></tr>";
            $(val).appendTo("#tableBody");
        }
    }
}

function loadTableDialog(cals){
    if(cals != ""){
        $("#tableBodyDialog").html("");
        var cant = 0;
        for(var cal in cals){
            cant++;
        }
        var i = 0;
        for(i = 0; i < cant; i++){
            val = "<tr><td>"+cals[i].serie+"</td><td>"+cals[i].season+"</td><td>"+cals[i].nroEp+"</td><td>"+cals[i].episode+"</td><td>"+cals[i].date+"</td></tr>";
            $(val).appendTo("#tableBodyDialog");
        }
        $('#dialogSeries').dialog('open');
    }
}

function selectCalendar(date){
    $('#notification').jGrowl("<b>LOADING...</b>");
    server.SelectByDate(date, loadTableDialog);
}

function sendBugReport(text){
    server.SendBugReportMail(text);
}

function savePreferences(){
    not = new Boolean($('#notify').attr("checked"));
    down = new Boolean($('#downloadFrom').attr("checked"));
    from = $("#comboFrom option:selected").text();
    format = $("#comboFormat option:selected").text();
    server.SavePreferences(not, down, from, format);
    $('#notification').jGrowl("<b>Preferences Saved</b>");
}

function completeDownloadsData(down){
    if(down != ""){
        var cant = 0;
        for(var d in down){
            cant++;
        }
        var i = 0;
        for(i = 0; i < cant; i++){
            var val = "<p><b>" + down[i].serie + "</p></b>";
            val += "<ul>";
            var links = down[i].links.split(",");
            for(var l in links){
                if(links[l] != ""){
                    val += "<li><a href='" + links[l] + "'>" + links[l] + "</a></li>";
                }
            }
            val += "</ul>";
            if(down[i].source != ""){
                val += "Source: " + down[i].source;
            }
            $(val).appendTo("#tabs-3");
        }
    }
}
